/*
 * @Description: 
 * @version: 
 * @Author: ShouJen
 * @Date: 2024-02-20 10:19:09
 * @LastEditors: ShouJen
 * @LastEditTime: 2025-03-19 10:56:28
 */
import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { isRelogin } from '@/config/axios/service'
import { getAccessToken } from '@/utils/auth'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { useUserStoreWithOut } from '@/store/modules/user'
import { usePermissionStoreWithOut } from '@/store/modules/permission'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()
// 路由不重定向白名单
const whiteList = [
  '/login',
  '/social-login',
  '/auth-redirect',
  '/bind',
  '/register',
  '/oauthLogin/gitee'
]

// 路由加载前
router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  if (getAccessToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 获取所有字典
      try {
        const userStore = useUserStoreWithOut()
        const permissionStore = usePermissionStoreWithOut()

        // 只有用户信息加载成功后，才去获取字典
        if (!userStore.getIsSetUser) {
          isRelogin.show = true
          await userStore.setUserInfoAction()
          isRelogin.show = false

          const dictStore = useDictStoreWithOut()
          if (!dictStore.getIsSetDict) {
            await dictStore.setDictMap()
          }

          // 生成动态路由
          await permissionStore.generateRoutes()
          permissionStore.getAddRouters.forEach((route) => {
            router.addRoute(route as unknown as RouteRecordRaw)
          })
          const redirectPath = from.query.redirect || to.path
          const redirect = decodeURIComponent(redirectPath as string)
          const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
          return next(nextData)
        }
        next()
      } catch (error) {
        next(`/login?redirect=${to.fullPath}`)
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
